package com.sinotn.ks.node.camera.receiver;

import java.io.File;
import java.util.Date;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;

import com.sinotn.SinotnLogger;
import com.sinotn.gson.GsonFacade;
import com.sinotn.ks.definition.AnswerPaper;
import com.sinotn.ks.definition.Computer;
import com.sinotn.ks.definition.ExamEngine;
import com.sinotn.ks.definition.Examinee;
import com.sinotn.ks.definition.Message;
import com.sinotn.ks.definition.MessageFile;
import com.sinotn.ks.definition.MessageReceiver;
import com.sinotn.ks.netty.message.SimpleMessage;
import com.sinotn.ks.node.camera.service.CameraService;
import com.sinotn.ks.node.camera.vo.CameraPhotoVO;
import com.sinotn.ks.node.runtime.FileStoreUtil;
import com.sinotn.util.FileUtil;

/**
 * 考试机摄像拍照记录
 *
 * @Title CameraPhotoReceiver.java
 * @Package com.sinotn.ks.node.camera.receiver
 * @Description Copyright: Copyright (c) 2015 Company:北京信诺软通
 *
 * @author <a href="mailto:xieqj@sinotn.com">谢启进</a>
 * @date 2017年6月22日 下午2:31:47
 * @version V1.0
 */
public class CameraPhotoReceiver implements MessageReceiver {
	@Autowired
	private ExamEngine examEngine;
	@Autowired
	private CameraService cameraService;

	private int type = 201;

	@Override
	public int getType() {
		return this.type;
	}

	public void setType(int type) {
		this.type = type;
	}

	@Override
	public void process(Computer computer, Message msg) {
		MessageFile[] files = null;
		try {
			files = msg.getFiles();
			if(this.examEngine.getRunState()==ExamEngine.STATE_AUTO_TEST){//自动测试不处理
				return;
			}
			// 如果没有可处理的照片文件，则返回
			if (files == null || files.length == 0) {
				return;
			}

			// 参数解析
			HashMap<?, ?> params = GsonFacade.fromJson(msg.getText(), HashMap.class);
			String examineeId = (String) params.get("examineeId");
			// 通过考试引擎查询考生信息，如果为空则返回
			Examinee examinee = examEngine.getExaminee(examineeId);
			if (examinee == null) {
				return;
			}

			// 默认是只有一张照片
			File file = files[0].getFile();
			// 保存文件到home目录，如果不存在则进行创建
			File directory = FileStoreUtil.getStoreFolder(examinee.getRoomId(), examineeId, true);
			directory=new File(directory, "camera");
			directory.mkdir();

			File destFile = new File(directory, System.currentTimeMillis() + ".jpg");
			FileUtil.copyFile(file, destFile);
			// 拷贝照片到ks-rs-web，供管理机访问图片
			File rsDirectory = new File(FileStoreUtil.getPhotoHttpFolder(examinee.getRoomId(), true), examineeId);
			if (!rsDirectory.exists()) {
				rsDirectory.mkdir();
			}
			File rsDestFile = new File(rsDirectory, destFile.getName());
			FileUtil.copyFile(file, rsDestFile);

			// 保存拍照监考记录到数据库
			Number phaseTmp = (Number) params.get("phase");
			byte phase = phaseTmp.byteValue();
			CameraPhotoVO cameraVo = this.getCameraPhotoInfo(examinee, examineeId, phase, destFile.getName());
			cameraService.addCameraPhoto(cameraVo);
		} catch (Throwable e) {
			SinotnLogger.DEBUG.error("考试机摄像拍照记录发生系统错误", e);
		} finally {
			// 发送消息给客户端
			SimpleMessage sm = new SimpleMessage(0, msg.getToken());
			computer.sendMessage(sm);
			if (files != null && files.length > 0) {
				for (int i = 0; i < files.length; i++) {
					files[i].delete();
				}
			}
		}
	}

	/**
	 * 设置监考照片的基本信息
	 * @param examinee
	 * @param examineeId
	 * @param phase
	 * @param filename
	 * @return
	 * @auth <a href="mailto:liyunfeng@sinotn.com">李云峰</a>
	 * @date 2017年6月26日 下午3:12:41
	 */
	private CameraPhotoVO getCameraPhotoInfo(Examinee examinee, String examineeId, byte phase, String filename) {
		CameraPhotoVO cameraVo = new CameraPhotoVO();
		cameraVo.setExamineeId(examineeId);
		cameraVo.setExamineeName(examinee.getName());
		cameraVo.setRoomId(examinee.getRoomId());

		AnswerPaper currentAnswerPaper = examinee.getCurrentAnswerPaper();
		if (currentAnswerPaper != null) {
			cameraVo.setAnswerPaperId(currentAnswerPaper.getId());
		}
		cameraVo.setExamInfoId(examinee.getExamItemId());
		//		cameraVo.setFixed(false);
		cameraVo.setState((byte) 0);

		cameraVo.setPhase(phase);
		cameraVo.setCreateTime(new Date());
		cameraVo.setPhotoPath(filename);
		return cameraVo;
	}
}
